package com.server.app;

import java.util.concurrent.ConcurrentHashMap;

import com.server.object.Player;
import com.webserver.server.net.UserInfo;

public class PlayerManager {
	private static PlayerManager instance;
	
	public static PlayerManager GetInstance(){
		if(instance == null){
			instance = new PlayerManager();
		}
		return instance;
	}
	
	private ConcurrentHashMap<Long,Player> playerMap = new ConcurrentHashMap<Long,Player>();
	
	/**
	 * 玩家登陆
	 * @param uid
	 * @return
	 */
	public void PlayerLogin(long appid, long uid, UserInfo userInfo, String data){
		synchronized (playerMap) {
			if(!playerMap.containsKey(uid)) {
				Player player_data = new Player();
				player_data.appid = appid;
				player_data.uid = uid;
				player_data.status = 0;
				player_data.data = data;
				player_data.userInfo = userInfo;
				playerMap.put(uid, player_data);
			}else {
				Player player_data = playerMap.get(uid);
				player_data.userInfo = userInfo;
				if(player_data.room != null) {
					player_data.room.RemovePlayer(uid);
					player_data.room = null;
				}
				
				player_data = new Player();
				player_data.appid = appid;
				player_data.uid = uid;
				player_data.status = 0;
				player_data.data = data;
				player_data.userInfo = userInfo;
				playerMap.put(uid, player_data);
			}
		}
	}
	
	/**
	 * 玩家离线
	 * @param uid
	 */
	public void PlayerLogout(long uid) {
		synchronized (playerMap) {
			if (playerMap.containsKey(uid)){
				Player player = playerMap.get(uid);
				if(player.room != null) {
					//TODO 从房间中移除玩家
					player.room.RemovePlayer(uid);
				}
				playerMap.remove(uid);
			}
		}	
	}
	
	/**
	 * 获取玩家数据
	 */
	public Player GetPlayer(long uid) {
		synchronized (playerMap) {
			if (playerMap.containsKey(uid)){
				return playerMap.get(uid);
			}
			return null;
		}
	}
}
